var express = require('express');
const axios = require('axios');

var router = express.Router();

/**
 * @api {get} /homepage 初始化渲染主页
 * @apiName 主页
 * @apiGroup index
 *
 *
 * @apiSuccess {String} firstname Firstname of the User.
 * @apiSuccess {String} lastname  Lastname of the User.
 */
router.get('/', function (req, res, next) {
    var pageNumber = 0
    var config = {
        method: 'get',
        baseURL: 'http://localhost:9022',
        url: '/tb-post/posts',
        params: {
            pageSize: 20,
            pageNumber: pageNumber
        },
        headers: {//指定响应头
            "Content-Type": "application/json;charset=utf-8",
            "Accept": "application/json"
        }
    }
    axios(config)
        .then(function (response) {
            console.log(response.data);
            if (response.data.code == 'success') {
                console.log("成功")
                // console.log(response.data)
                var data = response.data.data
                res.render('app/homepage', {
                    list: data
                });
            } else {
                // console.log(response);
                res.send({ err: -1, msg: "获取数据失败" })
                console.log("失败")
            }
        })
        .catch(function (error) {
            console.log(error);
            res.send({ err: -1, msg: "获取数据失败" })
            console.log("失败")
        });

})

/**
 * @api {get} /homepage/getPost 分页获取帖子
 * @apiName 主页
 * @apiGroup idnex
 *
 * @apiParam {String} pageNumber 第几页.
 *
 * @apiSuccess {String} firstname Firstname of the User.
 * @apiSuccess {String} lastname  Lastname of the User.
 */
router.get('/getPost', function (req, res, next) {
    let { pageNumber } = req.body
    var config = {
        method: 'get',
        baseURL: 'http://localhost:9022',
        url: '/tb-post/posts',
        params: {
            pageSize: 10,
            pageNumber: pageNumber
        },
        headers: {//指定响应头
            "Content-Type": "application/json;charset=utf-8",
            "Accept": "application/json"
        }
    }
    axios(config)
        .then(function (response) {
            console.log(response.data);
            if (response.data.code == 'success') {
                console.log("成功")
                res.send({ err: 0, msg: "获取数据成功", data: response.data.data })
            } else {
                // console.log(response);
                res.send({ err: -1, msg: "获取数据失败" })
                console.log("失败")
            }
        })
        .catch(function (error) {
            console.log(error);
            res.send({ err: -1, msg: "获取数据失败" })
            console.log("失败")
        });

})



module.exports = router;
